<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Shopcar;
use App\Model\Order;
use DB,Session;

class OrderController extends CommonController
{
    // 显示订单结算页面
    public function index()
    {
        // 获取用户信息
        $userid = Session::get('userData')->id;
        $address =  DB::table("user_address")->where("user_id", $userid)->get();
        // 获取购物车信息
        $data = Shopcar::getCartList();
        // 将购物车信息存入session
        $orderSession = $this->putSession($userid, $data);
        // 调用模板页面
        $addr_id = $orderSession[$userid]['addr_id'];
        return view("home.order.confirm", compact("address", "data", 'addr_id'));
    }
    
    // 模板页面修改收货地址
    public function changeAddress(Request $request)
    {
        $userid = Session::get('userData')->id;
        $addr_id = $request->get('id');
        
        // 检测是否合法
        $res = DB::table('user_address')->where('id', $addr_id)->where('user_id', $userid)->first();
        
        if(false !== $res){
            // 修改订单session中的地址id
            $orderData = Session::get('orderData');
            $orderData[$userid]['addr_id'] = $addr_id;
            // 重新写入session
            Session::put('orderData', $orderData);
            return response()->json(['status'=>1, 'info'=>'修改收货地址成功']);
        } else {
            return response()->json(['status'=>0, 'info'=>'收货地址错误']);
        }
    }
    
    // 提交订单
    public function processing()
    {
        // 获取用户信息及订单信息
        $userid = Session::get("userData")->id;
        $userOrderData = Session::get('orderData')[$userid];
        // 获取地址信息
        if(empty($userOrderData['addr_id'])){
            return back()->with('info', '请选择收货地址');
        }
        $address = DB::table("user_address")
                ->where("user_id", $userid)
                ->where("id", $userOrderData['addr_id'])
                ->first();
        // 生成订单信息
        $number = date("YmdHis").rand(1000, 9999);
        $ordertime = date('Y-m-d H:i:s');
        $goods = DB::table('goods');
        // 组装数据
        $orderdata = [];
        $orderdata['order_number'] = $number;
        $orderdata['user_id'] = $userid;
        $orderdata['order_name'] = $address->addr_consignee;
        $orderdata['order_tel'] = $address->addr_tel;
        $orderdata['order_address'] = $address->addr_province . ' ' . $address->addr_city . ' ' . $address->addr_county . ' ' . $address->addr_detail;
        $orderdata['order_code'] = $address->addr_postcode;
        $orderdata['order_time'] = $ordertime;
        
        $total = 0;
        foreach($userOrderData['goods'] as $k=>$c){
            // 写入数据到订单详情
            $detaildata[$k]['order_number'] = $number;
            $detaildata[$k]['goods_id'] = $c->goods_id;
            $detaildata[$k]['attr_id'] = $c->attr_id;
            $detaildata[$k]['order_goodsname'] = $goods->where('id',$c->goods_id)->pluck('goods_name');
            $detaildata[$k]['order_goodsnumber'] = $c->cart_num;
            $detaildata[$k]['order_price'] = $c->cart_price;
            $detaildata[$k]['order_totalprice'] = $c->cart_price * $c->cart_num;

            $total += $detaildata[$k]['order_totalprice'];
        }
        
        $orderdata['order_total'] = $total;
        
        // 执行插入数据库
        $res = $this->insertOrder($orderdata,$detaildata);
        if($res){
            return view('home.order.orderprocessing', compact("number", "total"));
        } else {
            return redirect('/tips')->with(['info'=>'结算失败', 'url'=>url('/confirm')]);
        }
    }
    
    // 插入订单到订单表
    protected function insertOrder($orderdata, $detailsdata)
    {
        DB::beginTransaction();
        // 插入订单表订单详情表
        $res1 = DB::table("order")->insert($orderdata);
        $res2 = DB::table("order_details")->insert($detailsdata);
        
        if($res1 && $res2){
            DB::commit();
            Session::put('ordernum', $orderdata['order_number']);
            // 清空购物车表
            Shopcar::where('user_id', $orderdata['user_id'])->delete();
            // 返回
            return true;
        } else {
            DB::rollback();
            return false;
        }
    }
    
    // 结算成功
    public function success()
    {
        // 支付成功，修改订单状态，时间
        $userid = Session::get("userData")->id;
        //查询order指定ID的数据
        $ordernum = Session::get('ordernum');
        $processing = DB::table("order")->where("order_number", $ordernum)->first();
        
        if($processing->order_status == 1 || $this->updateOrder($ordernum,$userid)){
            return view('home.order.ordersuccess', compact("processing"));
        } else {
            return back();
        }
    }
    
    // 将所需信息写入session
    protected function putSession($uid, $data)
    {
        // 获取session数据
        if(Session::has('orderData')){
            $orderSession = Session::get('orderData');
        }
        // 接收购物车信息
        $orderSession[$uid]['goods'] = $data;
        if(!isset($orderSession[$uid]['addr_id'])){
            $orderSession[$uid]['addr_id'] = DB::table('user_address')->where('user_id', $uid)
                ->where('addr_status', 1)
                ->pluck('id');
        }
        // 写入session
        Session::put('orderData', $orderSession);
        return $orderSession;
    }
    
    protected function updateOrder($ordernum,$userid)
    {
        $paytime = date('Y-m-d H:i:s');
        // 修改订单表的订单状态为已支付
        DB::beginTransaction();
        $res1 = DB::table('order')->where('order_number',$ordernum)->update(['order_status'=>1, 'order_paytime'=>$paytime]);
        // 修改订单详情表的订单状态
        $res2 = DB::table('order_details')->where('order_number', $ordernum)->update(['order_status'=>1]);

        if(false !== $res1 && false !== $res2){
            // 增加商品销量
            $goodsid = DB::table('order_details')->where('order_number', $ordernum)->lists('order_goodsnumber', 'goods_id');
            foreach($goodsid as $k=>$v){
                $db = DB::table('goods')->where('id', $k);
                $db->increment('goods_salenum', $v);
                $db->decrement('goods_num', $v);
            }
            // 销毁session
            $userOrderData = Session::get('orderData');
            if(count($userOrderData) > 1){
                unset($userOrderData[$userid]);
                Session::put($userOrderData);
            } else {
                Session::forget('orderData');
            }
            DB::commit();
            return true;
        } else {
            DB::rollback();
            return back();
        }
    }
    
    // 确认收货
    public function shou($id)
    {
        $userid = Session::get('userData')->id;
        // 获取订单信息
        $details = DB::table('order_details')->where('id', $id)->first();
        $order = Order::where('user_id', $userid)->where('order_number', $details->order_number)->first();
        if(!$order){
            return back()->with(['error'=>'确认收货失败']);
        }
        
        if($details->order_status == 2){
            $res = DB::table('order_details')->where('id', $id)->update(['order_status'=>3]);
            if($res){
                return back()->with(['error'=>'确认收货成功']);
            } else {
                return back()->with(['error'=>'确认收货失败']);
            }
        } else {
            return back()->with(['error'=>'确认收货失败']);
        }
    }
}
